//
//  RBMeFootView.m
//  Budejie
//
//  Created by 华杨科技 on 2017/10/12.
//  Copyright © 2017年 饶波. All rights reserved.
//

#import "RBMeFootView.h"
#import <AFNetworking.h>
#import <MJExtension.h>

#import "RBMeSquare.h"
#import "RBMeSquareButton.h"
#import "RBMeWebViewController.h"
#import <SafariServices/SafariServices.h>


@interface RBMeFootView()
/**模型字典*/
//@property (nonatomic, strong) NSMutableDictionary <NSString *, RBMeSquare *>*squarsDic;
@end

@implementation RBMeFootView

//- (NSMutableDictionary<NSString *,RBMeSquare *> *)squarsDic {
//    if (!_squarsDic) {
//        _squarsDic = [NSMutableDictionary dictionary];
//    }
//    return _squarsDic;
//}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        // 参数
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"a"] = @"square";
        params[@"c"] = @"topic";
        
        // 请求
        [[AFHTTPSessionManager manager] GET:@"http://api.budejie.com/api/api_open.php" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * responseObject) {
            
            // 小技巧，将服务器返回数据以plist形式保存到桌面
            //            [responseObject writeToFile:@"/Users/huayangkeji/me.plist" atomically:YES];
            
            NSArray *modelArr = [RBMeSquare mj_objectArrayWithKeyValuesArray:responseObject[@"square_list"]];            
            
            [self createSquares:modelArr];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {            
            NSLog(@"请求失败:%@",error); 
        }];

    }
    
    return self;
}

- (void)createSquares:(NSArray *)array 
{    
    // 按钮尺寸
    NSInteger maxColumnCount = 4; // 最大列数
    CGFloat buttonW = self.frame.size.width / maxColumnCount;
    CGFloat buttonH = buttonW;
    
    // 创建按钮
    for (NSInteger i =0; i < array.count; i++) {
        // i位置对应的模型数据
        RBMeSquare *square = array[i];
        
        // 创建按钮
        RBMeSquareButton *button = [RBMeSquareButton buttonWithType:UIButtonTypeCustom];
        [self addSubview:button];
     
        // 设置frame
        button.rb_x = (i % maxColumnCount) * buttonW;
        button.rb_y = (i / maxColumnCount) * buttonH;
        // 方式一:设置分割线的最懒的方法。tableView.footView默认灰色。1.设置button 背景为白色。2.在让宽高，各自-1px
        // 方式二:让美工搞个分割线的背景图片，设置button的背景图片即可
        button.rb_width = buttonW ; // button.rb_width = buttonW - 1;
        button.rb_height = buttonH; // button.rb_height = buttonH - 1;
                
        // 设置数据
        button.square = square;
        //        self.squarsDic[button.description] = square;
        
        // 添加点击事件
        [button addTarget:self action:@selector(clickButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    // 设置footView 的高度
//    self.rb_height = self.subviews.lastObject.rb_bottom;
    NSUInteger arrcounts = array.count;
    
//    NSUInteger rowCounts = 0;
//    if (arrcounts % maxColumnCount == 0) {
//        rowCounts = arrcounts / maxColumnCount;
//    }else{
//        rowCounts = arrcounts / maxColumnCount + 1;
//    }
    
//    NSUInteger rowCounts = arrcounts / maxColumnCount;
//    if (arrcounts % maxColumnCount ) {
//        rowCounts += 1;
//    }

    // 计算总页数，总函数通用公式:总行数(总页数) = (总个数 + 每一行最多显示个数 - 1) / 每一行最多显示个数
    NSUInteger pagecounts = (arrcounts + maxColumnCount - 1 ) / maxColumnCount;
    self.rb_height = pagecounts * buttonH; // 行数 * btn高度
    
    // 10-12 设置tableView的contentSize,解决tabbar盖住tableView的问题
    UITableView *tableView = (UITableView *)self.superview;
    tableView.tableFooterView = self; // 要不要无所谓
    [tableView reloadData]; // 刷新数据(其实也会重新计算contentSize) 完美解决底部多出的20px
//    tableView.contentSize = CGSizeMake(0, self.rb_bottom); // 不靠谱
    
}
- (void)clickButtonAction:(RBMeSquareButton *)btn
{
    RBMeSquare *square = btn.square;
    NSString *url = square.url;
    NSLog(@"%@",url);

    /*****查找字符串的常见方法*******/
    NSString *testStr = @"mod://fsdfhttpdasdsa";
//    [@"mod://fsdfhttpdasdsa" containsString:@"http"]; YES
//    [@"mod://fsdfhttpdasdsa" hasSuffix:@"sa"]; YES
//    [@"mod://fsdfhttpdasdsa" hasPrefix:"http"] NO
    
    // 如果location == 0,说明是以http开头
    // 如果location == NSNotFound 或者 length == 0,说明没有找到对应的字符串
    NSRange range = [testStr rangeOfString:@"http"];
    NSLog(@"%@",range.length ? @"存在" : @"");
            
    
    if ([url hasPrefix:@"http"]) {
        NSLog(@"使用webView加载网页");
        
  

        /**SFSafariViewController iOS9 可现实进度条***/
//        SFSafariViewController *webViewVC = [[SFSafariViewController alloc] initWithURL:[NSURL URLWithString:url]];
//        UITabBarController *tabbarVC = (UITabBarController *)self.window.rootViewController; // 和上面的作用相同
//        [tabbarVC presentViewController:webViewVC animated:YES completion:nil];

        // 创建webViewVC 
        RBMeWebViewController *webViewVC = [[RBMeWebViewController alloc] init];
        webViewVC.url = url;
        
        /**获取viewController**/
        //[UIApplication sharedApplication].keyWindow.rootViewController;
        UITabBarController *tabbarVC = (UITabBarController *)self.window.rootViewController; // 和上面的作用相同
//        UINavigationController *naVC = tabbarVC.childViewControllers.firstObject;
        UINavigationController *naVC = tabbarVC.selectedViewController;
        [naVC pushViewController:webViewVC animated:YES];
        
    } else if ([square.url hasPrefix:@"mod"]){
        if ([square.url hasSuffix:@"BDJ_To_Check"]) {
            NSLog(@"跳转到审帖");
        } else if ([square.url hasSuffix:@"BDJ_To_RecentHot"]){
            NSLog(@"跳转到每日排行");
        }else{
            NSLog(@"其他处理");
        }
    }else {
        NSLog(@"不是http 或者 mod 协议");
    }
}
@end
